<?php

namespace App\Http\Controllers\CRM;

use App\Enums\AssistantStatus;
use App\Enums\OrderItemType;
use App\Enums\UserType;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\CRM\AssistantListRequest;
use App\Http\Resources\CRM\UserResource;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\User;
use App\Models\UserRole;
use Illuminate\Http\Request;

class AssistantController extends Controller
{
    public function getList(AssistantListRequest $request)
    {
        $status = $request->status;

        $query = User::where('store_id', $request->store_id)
            ->where('type', UserType::Assistant)
            ->with("role");

        if (!empty($status))
            $query = $query->where('assistant_status', $status);

        $users = $query->latest()->get();

        return UserResource::collection($users);
    }

    public function getInfo(User $user)
    {
        $assistantStatus = $user->assistant_status;
        $startAt = date('Y-m-d 00:00:00');
        $endAt = date('Y-m-d 23:59:59');

        $orderItemQuery = OrderItem::where('assistant_user_id', $user->id)
            ->whereNotNull('end_at')
            ->whereBetween('created_at', [$startAt, $endAt]);
        $assistantOrderItems = $orderItemQuery->get();

        $orderIds = $orderItemQuery->pluck('order_id');
        $orderQuery = Order::whereIn('id', $orderIds);
        $orders = $orderQuery->with('items.table')->get();

        //今日台桌
        $todayTables = [];
        //今日台费金额
        $todayTableMoney = 0;
        //今日助教费
        $todayAssistantMoney = $orderItemQuery->sum('money');
        //今日商品费
        $todayGoodsMoney = OrderItem::whereIn('order_id', $orderIds)
            ->where('type', OrderItemType::Goods)
            ->sum('money');
        /**
         * @var Order $order
         */
        foreach ($orders as $order) {
            $tableItem = $order->getTableItem();
            if (!empty($tableItem)) {

                $todayTables[] = [
                    'id' => $tableItem->table_id,
                    'table_name' => $tableItem->table->name,
                    'start_at' => $tableItem->start_at,
                    'end_at' => $tableItem->end_at,
                    'total_minutes' => $tableItem->getTotalMinutes($endAt),
                ];
                $todayTableMoney += $tableItem->money;
            }
        }
        //今日总金额
        $todayTotalMoney = $todayTableMoney + $todayAssistantMoney + $todayGoodsMoney;
        //今日总时长
        $todayTotalMinutes = 0;
        //今日内虚拟时长
        $todayInnerVirtualMinutes = 0;
        //今日外虚拟时长
        $todayOutVirtualMinutes = 0;
        foreach ($assistantOrderItems as $item) {
            $todayTotalMinutes += $item->getTotalMinutes($endAt);
        }
        //总上钟数
        $totalClockCount = OrderItem::where('assistant_user_id', $user->id)->count();
        //本月上钟数
        $monthClockCount = OrderItem::where('assistant_user_id', $user->id)
            ->whereBetween('created_at', [date('Y-m-01 00:00:00'), date('Y-m-t 23:59:59')])
            ->count();
        //本周上钟数
        $weekClockCount = OrderItem::where('assistant_user_id', $user->id)
            ->whereBetween('created_at', [date('Y-m-d 00:00:00', strtotime('this week Monday')), date('Y-m-d 23:59:59', strtotime('this week Sunday'))])
            ->count();

        if ($assistantStatus == AssistantStatus::OnDuty || $assistantStatus == AssistantStatus::InnerVirtual || $assistantStatus == AssistantStatus::OuterVirtual) {
            $currentOrderItem = OrderItem::where('assistant_user_id', $user->id)
                ->whereNull('end_at')
                ->first();
            $currentOrder = $currentOrderItem->order;
            $currentTableItem = $currentOrder->getTableItem();
            $current = [
                'table' => [
                    'id' => $currentTableItem->table_id,
                    'table_name' => $currentTableItem->table->name,
                    'start_at' => $currentTableItem->start_at,
                    'total_minutes' => $currentTableItem->getTotalMinutes(now()),
                ],
            ];
        }

        return ApiResponseHelper::json([
            'assistant_status' => $assistantStatus,
            'today_tables' => $todayTables,
            'today_table_money' => $todayTableMoney,
            'today_assistant_money' => $todayAssistantMoney,
            'today_goods_money' => $todayGoodsMoney,
            'today_total_money' => $todayTotalMoney,
            'today_total_minutes' => $todayTotalMinutes,
            'today_inner_virtual_minutes' => $todayInnerVirtualMinutes,
            'today_out_virtual_minutes' => $todayOutVirtualMinutes,
            'total_clock_count' => $totalClockCount,
            'month_clock_count' => $monthClockCount,
            'week_clock_count' => $weekClockCount,
            'current' => $current ?? null,
            'assistant' => $user,
        ]);
    }
}
